package com.atguigu.gmall.user.api;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 钟涛
 * @version 1.0
 * @description: TODO
 * @date 2021/12/21 9:44
 */
@RestController
@RequestMapping("/api/user")
public class LoginController {
    @Autowired
    private UserInfoService userInfoService;
    /**
     * 处理登录请求：
     *    登录成功后，把登录信息返回后，前端会把用户信息(token)保存起来,
     *    以后每次请求都会以请求头的方式带上。
     * @param userInfo
     * @return
     */
    @PostMapping("/passport/login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) throws JsonProcessingException {

        UserInfo userInfo1 = userInfoService.login(userInfo.getLoginName(),userInfo.getPasswd());
        if(userInfo1!=null){
            //处理登录成功的用户信息,返回一个map，map中有token和nickName
            String ipAddress = IpUtil.getIpAddress(request);
            Map<String,String> infoMap = userInfoService.handleLoginInfo(userInfo1,ipAddress);
            return Result.ok(infoMap);
        }else{
            Result<String> result = Result.fail();
            result.setMessage("账号密码错误");
            return result;
        }

    }

    /**
     * 处理登出请求
     * @param
     * @return
     */
    @GetMapping("/passport/logout")
    public Result logout(@RequestHeader("token") String token) throws JsonProcessingException {
        userInfoService.logout(token);
        return Result.ok();

    }
}
